package metier;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import webEquipeRechercheGwt.client.entityMirror.PaperMirror;
import webEquipeRechercheGwt.client.entityMirror.PersonMirror;

@Entity
@Table(name="PAPER")
@NamedQueries(
		@NamedQuery(name="getPapers",
				query="select p from Paper p " +
				"order by p.title")
			)
public class Paper implements Serializable {

	private static final long serialVersionUID = -6778579516282281694L;
	
	private int id;
	private String title;
	private String state;
	private String url4pdf;
	private Collection<Person> authors;
	private PaperMirror loaded;
	
	// Accessors
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getUrl4pdf() {
		return url4pdf;
	}
	public void setUrl4pdf(String url4pdf) {
		this.url4pdf = url4pdf;
	}
	@ManyToMany(mappedBy="papers")
	public Collection<Person> getAuthors() {
		return authors;
	}
	public void setAuthors(Collection<Person> authors) {
		this.authors = authors;
	}
	public void addAuthor(Person p){
		authors.add(p);
	}
	
	public void fullLoad(){
		Iterator<Person> it = authors.iterator();
		while(it.hasNext()){
			Person p = it.next();
			p.toString();
		}
	}
	
	public PaperMirror getMirror(){
		if(loaded==null){
			loaded = new PaperMirror();
			loaded.setId(id);
			loaded.setState(state);
			loaded.setTitle(title);
			loaded.setUrl4pdf(url4pdf);
			Collection<PersonMirror> authorMirrors = new ArrayList<PersonMirror>();
			for(Person p : authors){
				authorMirrors.add(p.getMirror());
			}
			loaded.setAuthors(authorMirrors);
		}
		return loaded;
	}

}
